package com.api.test;

import javax.security.auth.login.LoginException;

import com.zyncro.remoting.rest.RestProxyFactoryBean;
import com.zyncro.remoting.rest.client.RestProxyFactory;
import com.zyncro.remoting.rest.client.oauth.OAuthRestConnectionFactory;

public class ApiRemotingImpl implements Api {

	private RestProxyFactory proxyFactory;

	private OAuthRestConnectionFactory connectionFactory;

	private String serviceUrl;

	private String accessKey;

	public ApiRemotingImpl(OAuthRestConnectionFactory connectionFactory, RestProxyFactory proxyFactory, String serviceUrl) {

		if (proxyFactory == null || connectionFactory == null || serviceUrl == null) {

			throw new IllegalArgumentException("ConnectionFactory, ProxyFactory and serviceUrl cannot be null");
		}

		this.proxyFactory = proxyFactory;
		this.connectionFactory = connectionFactory;
		this.serviceUrl = serviceUrl;
	}

	public void login(String username, String password) {

		if (username == null || password == null) {

			throw new IllegalStateException("Username and password cannot be null");
		}

		try {
			accessKey = connectionFactory.login(username, password);

		} catch (LoginException e) {

			throw new IllegalStateException(String.format("Couldn't login username '%s' password '%s'", username, password), e);
		}
	}

	public <T> T getService(Class<T> serviceClass) {

		RestProxyFactoryBean proxy = new RestProxyFactoryBean();

		proxy.setServiceInterface(serviceClass);
		proxy.setServiceUrl(serviceUrl);
		proxy.setProxyFactory(proxyFactory);

		proxy.afterPropertiesSet();
		@SuppressWarnings("unchecked")
		T service = (T) proxy.getObject();

		return service;
	}

	@Override
	public String getAccessKey() {

		if (accessKey != null) {

			return accessKey;
		} else {
			throw new IllegalStateException("User is not logged in");
		}
	}
}
